C中的動態記憶體分配允許程式在運行時(而不是在編譯時)管理內存。當數據結構的大小或所需的記憶體量不知道時,可用這招。 C中動態記憶體分配的核心函數是malloc(),calloc(),realloc()和free(),所有這些函數都在 header stdlib.h 中找到。
以下為一簡單例子
// 計算使用者輸入整數的總和
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// 分配失敗
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// 釋放記憶體
free(ptr);
return 0;
}